package com.heima.article.listener;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.ApArticleConfigService;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.model.article.pojos.ApArticleConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * app文章上下架状态修改的监听器
 */
@Slf4j
@Component
public class ApArticleDownOrUpListener {

    @Autowired
    private ApArticleConfigService apArticleConfigService;

    @KafkaListener(topics = WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC)
    public void msg(ConsumerRecord<String,String> consumerRecord){
        if(consumerRecord!=null){
            //1.获取消息里value的JSON字符串
            String json = consumerRecord.value();

            //2.将JSON转为MAP对象
            Map map = JSON.parseObject(json, Map.class);

            //3.获取articleId和enable
            Long articleId = Long.valueOf(String.valueOf(map.get("articleId"))); //app文章id
            Integer enable = Integer.valueOf(String.valueOf(map.get("enable"))); //自媒体文章上下架状态

            //4.设置isDown的值
            boolean isDown = true; //已下架 1
            if(enable==1){
                isDown = false; //未下架（已上架）0
            }

            //5.更新ap_article_config的is_down的值  update ap_article_config set is_down=? where article_id=?
            boolean result = apArticleConfigService.lambdaUpdate()
                    .eq(ApArticleConfig::getArticleId, articleId) //更新条件
                    .set(ApArticleConfig::getIsDown, isDown) //更新的数据
                    .update();
            log.info("[app文章上下架状态更新] 更新结果：{}，文章id：{}", result, articleId);
        }
    }
}
